package cn.ys.base.interceptor;

import cn.ys.base.anno.PreAuthorize;
import cn.ys.base.jwt.JwtUtils;
import cn.ys.base.jwt.Payload;
import cn.ys.base.jwt.RsaUtils;
import cn.ys.base.jwt.UserInfo;
import cn.ys.base.util.ThreadLocalUtil;
import cn.ys.system.mapper.PermissionMapper;
import cn.ys.user.domain.Logininfo;
import cn.ys.user.domain.User;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.security.PublicKey;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Component
public class LoginInterceptor implements HandlerInterceptor {

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private PermissionMapper permissionMapper;

    @Value("${jwt.pub}")
    private String jwtPub;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 6.如果能走到这里，说明token为空或者是Redis中用户信息为空，那么以未登录进行处理
        // 6.1.设置编码字符集
        response.setCharacterEncoding("UTF-8");
        // 6.2.设置响应参数类型为JSON
        response.setContentType("application/json;charset=UTF-8");
        // 1.从header头中取出token
        String token = request.getHeader("token");
        // 2.判断token是否存在
        if(StringUtils.isNotBlank(token)){
            // 3.token如果存在取出对应的logininfo
            // Logininfo logininfo = (Logininfo) redisTemplate.opsForValue().get(token);
            // 2 解析token里面内容
            PublicKey publicKey = RsaUtils.getPublicKey(JwtUtils.class.getClassLoader().getResource(jwtPub).getFile());
            Payload<UserInfo> payload = JwtUtils.getInfoFromToken(token, publicKey, UserInfo.class);
            // 4.判断logininfo是否为空
            if(payload.getUserInfo() != null){
                Logininfo logininfo = payload.getUserInfo().getLogininfo();
                // todo
                ThreadLocalUtil.setUserInfo(payload.getUserInfo());
                // 判断是否是后台人员
                if(0 == logininfo.getType()){
                    // 查询有那些权限
                    // List<String> snList =  permissionMapper.findByLogininfoId(logininfo.getId());
                    List<String> snList = payload.getUserInfo().getPermissions();
                    // 获取请求controller的方法上注解
                    HandlerMethod handlerMethod = (HandlerMethod) handler;
                    // 获取自定义注解
                    PreAuthorize preAuthorize = handlerMethod.getMethodAnnotation(PreAuthorize.class);
                    if (null != preAuthorize){
                        String sn = preAuthorize.sn();
                        // 判断 当前人拥有得权限 是否包含这个sn 如果不包含 就拦截 返回 noPermission
                        if (!snList.contains(sn)){
                            // 6.3.获取到打印流,并设置响应数据
                            PrintWriter writer = response.getWriter();
                            writer.write("{\"success\":false,\"resultObj\":\"noPermission\"}");
                            // 6.4.刷新、关流
                            writer.flush();
                            writer.close();
                            return false;
                        }
                    }
                }
                // 5.不为空刷新时间
                // redisTemplate.opsForValue().set(token, logininfo,30, TimeUnit.MINUTES);
                return true;
            }
        }
        // 6.3.获取到打印流,并设置响应数据
        PrintWriter writer = response.getWriter();
        writer.write("{\"success\":false,\"resultObj\":\"noLogin\"}");
        // 6.4.刷新、关流
        writer.flush();
        writer.close();
        return false;
    }
}
